package com.xiaomi.service.impl;

import com.xiaomi.constant.MessageConstant;
import com.xiaomi.dto.VehicleDTO;
import com.xiaomi.entity.Vehicle;
import com.xiaomi.exception.BusinessException;
import com.xiaomi.exception.DuplicateKeyException;
import com.xiaomi.mapper.VehicleMapper;
import com.xiaomi.service.VehicleService;
import com.xiaomi.utils.RandomVidUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    private VehicleMapper vehicleMapper;

    /**
     * 新增车辆
     * @param vehicle
     */
    @Transactional
    @Override
    public Vehicle insert(Vehicle vehicle) {
        final int MAX_RETRY = 3; // 最大重试次数
        int retryCount = 0;

        while (retryCount < MAX_RETRY) {
            String vid = RandomVidUtils.getVid();
            vehicle.setVid(vid);
            vehicle.setCreateTime(LocalDateTime.now());
            vehicle.setUpdateTime(LocalDateTime.now());

            try {
                vehicleMapper.insert(vehicle);
                break;
            } catch (DuplicateKeyException e) {
                retryCount++;
                if (retryCount >= MAX_RETRY) {
                    throw new BusinessException(e.getCode(),"生成车辆VID失败，请检查VID生成规则");
                }
            }
        }
        return vehicle;
    }

    /**
     * 根据id查询车辆信息
     * @param FrameNumber
     * @return
     */
    @Override
    public Vehicle getById(Long FrameNumber) {
        Vehicle vehicle = vehicleMapper.getById(FrameNumber);
        if (vehicle == null) {
            throw new BusinessException(404, MessageConstant.QUERY_VEHICLE_BY_ID_FAIL);
        }
        return vehicle;
    }

    /**
     * 更新车辆信息
     * @param vehicleDTO
     */
    @Override
    public void update(VehicleDTO vehicleDTO) {
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleDTO, vehicle);
        vehicle.setUpdateTime(LocalDateTime.now());
        vehicleMapper.update(vehicle);
    }

    /**
     * 根据车架编号删除车辆信息
     * @param frameNumber
     */
    @Override
    public void deleteById(Long frameNumber) {
        vehicleMapper.deleteById(frameNumber);
        if(vehicleMapper.getById(frameNumber)!=null){
            throw new BusinessException(404, MessageConstant.DELETE_VEHICLE_FAIL);
        }
    }

    @Override
    public List<Vehicle> getAllVehicles() {
        return vehicleMapper.getAll();
    }

}
